import { useEffect, useState } from 'react';
import { Card, Image, Typography, List, Row, Col, Spin, Button, Empty } from 'antd';
import axios from 'axios';
import { useParams, Link } from 'react-router-dom';
import './index.css'; // 确保导入了 CSS 文件
import { LeftOutlined } from '@ant-design/icons';

const { Meta } = Card;
const { Title } = Typography;

const SpeechSecondPage = () => {
  const [book, setBook] = useState(null);
  const [chapters, setChapters] = useState([]);
  const [loading, setLoading] = useState(true);
  const { bookId } = useParams();

  useEffect(() => {
    if (!bookId) {
      console.error('Book ID is missing in the URL.');
      return;
    }

    const fetchBookDetails = async () => {
      try {
        const response = await axios.get(`/api/books/${bookId}`);
        console.log('Fetched book details:', response.data); // 检查数据
        if (response.data && response.data.code === 200 && response.data.data) {
          setBook(response.data.data);
        } else {
          console.error('Unexpected data format for book details:', response.data);
          setBook(null);
        }
      } catch (error) {
        console.error('Error fetching book details:', error);
      }
    };

    const fetchChapters = async (id) => {
      try {
        const response = await axios.get(`/api/chapters/byBookId?bookId=${id}`);
        console.log('Fetched chapters:', response.data); // 检查数据
        if (response.data && response.data.code === 200 && Array.isArray(response.data.data)) {
          setChapters(response.data.data);
        } else {
          console.error('Unexpected data format for chapters:', response.data);
          setChapters([]);
        }
      } catch (error) {
        console.error('Error fetching chapters:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchBookDetails();
    fetchChapters(bookId); // 确保传入 bookId
  }, [bookId]);

  if (loading) {
    return (
      <div style={{ textAlign: 'center', marginTop: '50px' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!book) {
    return <div>Book not found</div>;
  }

  const handleGoBack = (event) => {
    event.preventDefault(); // 阻止默认的链接行为
    window.history.back(); // 返回上一页
};

  return (
    <div className="speech-second-page">
      <Row gutter={[24, 24]}>
        <Col span={24} style={{ marginBottom: 15 }}>
          <Button icon={<LeftOutlined />} type="primary" onClick={handleGoBack} style={{ width:100,display: 'flex', alignItems: 'center' ,color:'#23153C',background:'white',marginLeft:30,marginTop:30}}>
            <span style={{ marginLeft: 3 }}>返回</span>
          </Button>
        </Col>
        <Col span={12}>
          <Card
            className="speechS-centered-card"
            cover={
              book && book.picture ? (
                <Image 
                  src={`data:image/png;base64,${book.picture}`} 
                  alt={book.title}
                  preview={false} 
                  style={{
                    width: '100%',
                    height: 'auto',
                    borderRadius: '8px',
                    objectFit: 'cover'
                  }} 
                />
              ) : (
                <div style={{ width: '600px', height: '400px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <Empty description="No image available" />
                </div>
              )
            }
            title={<div style={{ textAlign: 'center', fontWeight: 'bold' }}>✨ {book.title}</div>}
            bordered={false}
            style={{ marginBottom: 15 }}
          >
            <Meta description={book.description} />
          </Card>
        </Col>
        <Col span={12}>
          <Title level={7}>💬Chapters</Title>
          <div className="speechS-chapter-list-container"> {/* 添加类名 */}
            {chapters.length > 0 ? (
              <List
                itemLayout="horizontal"
                dataSource={chapters}
                renderItem={(item) => (
                  <List.Item className="speechS-chapter-item"> {/* 添加类名 */}
                    <List.Item.Meta
                      title={<Link className="speechS-link" style={{ color: '#23153C', fontSize: 17 }} to={`/dialogue/${bookId}/chapter/${item.chapterId}/sentence`}>{item.title}</Link>}
                      description={<span className="speechS-description" style={{ color: '#23153C' }}>{item.etitle}</span>}
                    />
                  </List.Item>
                )}
              />
            ) : (
              <Empty description="No chapters available" />
            )}
          </div>
        </Col>
      </Row>
    </div>
  );
};

export default SpeechSecondPage;